package com.anjie.powerproject.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Http访问工具类
 */
public class HttpClientUtil {

    public static Map post(String url, Map<String,Object> paramMap) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        StringBuffer params = new StringBuffer();
        paramMap.forEach((k,v) -> params.append(k + "=" + v + "&"));
        HttpPost httpPost = new HttpPost(url + "?" + params);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        CloseableHttpResponse response = null;
        Map resultMap = new HashMap();

        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                resultMap = JSONObject.parseObject(EntityUtils.toString(responseEntity));
                resultMap.put("success", true);
            }
        } catch (ParseException | IOException e) {
            resultMap.put("success", false);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }
}